package com.atguigu.tingshu.config;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

/**
 * ClassName: ReturnAndConfimConfig
 * Package: com.atguigu.tingshu.config
 * Description:消息确认和消息退回模式的配置
 */
@Configuration
@Slf4j
public class ReturnAndConfirmConfig {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 配置消息确认和消息退回
     */
    @PostConstruct
    public void init() {

        rabbitTemplate.setMandatory(true);

        //开启确认模式
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack) {
                //消息投递到交换机失败
                //todo:定时任务做消息重发
                log.error("消息投递到交换机失败,.......");
            }
        });

        //开启退回模式

        rabbitTemplate.setReturnsCallback(returned->{
            //消息投递到队列失败
            String exchange = returned.getExchange();
            String routingKey = returned.getRoutingKey();
            int replyCode = returned.getReplyCode();
            String replyText = returned.getReplyText();
            //todo:定时任务做消息重发
            log.error("消息投递到队列失败,交换机为:{},路由为:{},replyCode为:{},replyText为:{}",
                    exchange, routingKey, replyCode , replyText);
        });
    }

}
